"""
多股票对比分析工具
"""

import pandas as pd
import logging
from typing import List, Dict


class MultiStockAnalyzer:
    """多股票对比分析类"""
    
    def __init__(self):
        # 延迟导入，避免循环导入
        from core.data_fetcher import StockDataFetcherV2
        self.fetcher = StockDataFetcherV2()
        self.results = []
    
    def analyze_multiple_stocks(self, stock_codes: List[str], days=250) -> pd.DataFrame:
        """
        对比分析多只股票
        
        参数:
            stock_codes: 股票代码列表
            days: 历史数据天数
        
        返回:
            DataFrame: 对比结果
        """
        logging.info(f"开始对比分析 {len(stock_codes)} 只股票")
        
        comparison_data = []
        
        for stock_code in stock_codes:
            try:
                logging.info(f"分析股票: {stock_code}")
                
                # 获取数据
                realtime_data = self.fetcher.get_realtime_data(stock_code)
                hist_data = self.fetcher.get_historical_data(stock_code, days=days)
                
                if hist_data is None or len(hist_data) == 0:
                    logging.warning(f"股票 {stock_code} 数据获取失败，跳过")
                    continue
                
                # 延迟导入，避免循环导入
                from core.technical_analysis import TechnicalIndicators
                from core.quantitative_analysis import QuantitativeAnalyzer
                
                # 计算技术指标
                hist_data = TechnicalIndicators.calculate_all_indicators(hist_data)
                
                # 量化分析
                analyzer = QuantitativeAnalyzer(realtime_data, hist_data)
                signals, score = analyzer.comprehensive_analysis()
                recommendation = analyzer.generate_recommendation(score)
                
                # ===== 交易决策分析 ===== V2.3
                from utils.trading_advisor import TradingAdvisor
                
                advisor = TradingAdvisor(realtime_data, hist_data)
                trading_plan = advisor.comprehensive_trading_plan()
                
                # 提取关键交易决策信息
                position_advice = trading_plan.get('position_advice', {})
                entry_price = trading_plan.get('entry_price', {})
                multi_strategy = trading_plan.get('multi_strategy', {})
                risk_reward = trading_plan.get('risk_reward', {})
                price_levels = trading_plan.get('price_levels', {})
                
                # 整理结果
                latest = hist_data.iloc[-1]
                
                result = {
                    '股票代码': stock_code,
                    '股票名称': realtime_data['股票名称'] if realtime_data else stock_code,
                    '综合评分': round(score, 2),
                    '投资建议': recommendation[0],
                    # 交易决策信息
                    '仓位建议': position_advice.get('action', 'N/A'),
                    '仓位变化': position_advice.get('position_change', 'N/A'),
                    '稳健买入价': entry_price.get('moderate_entry', 'N/A'),
                    '止损价': entry_price.get('stop_loss', 'N/A'),
                    '风险收益比': f"{risk_reward.get('risk_reward_ratio', 0):.2f}:1" if risk_reward.get('risk_reward_ratio') else 'N/A',
                    '多周期评级': multi_strategy.get('overall_rating', 'N/A'),
                }
                
                # 添加实时数据（安全处理None值）
                if realtime_data:
                    # 安全获取函数，避免None值导致错误
                    def safe_get(data, key, default='N/A'):
                        value = data.get(key, default)
                        return value if value is not None else default
                    
                    def safe_divide(numerator, denominator, decimals=2, default='N/A'):
                        if numerator is None or denominator is None or denominator == 0:
                            return default
                        try:
                            return round(numerator / denominator, decimals)
                        except:
                            return default
                    
                    result.update({
                        '最新价': safe_get(realtime_data, '最新价'),
                        '涨跌幅(%)': safe_get(realtime_data, '涨跌幅'),
                        '换手率(%)': safe_get(realtime_data, '换手率'),
                        '量比': safe_get(realtime_data, '量比'),
                        '市盈率': safe_get(realtime_data, '市盈率'),
                        '总市值(亿)': safe_divide(realtime_data.get('总市值'), 100000000),
                    })
                
                # 添加技术指标
                if 'MA20' in latest:
                    result['MA20'] = round(latest['MA20'], 2) if pd.notna(latest['MA20']) else None
                if 'RSI6' in latest:
                    result['RSI6'] = round(latest['RSI6'], 2) if pd.notna(latest['RSI6']) else None
                if 'K' in latest:
                    result['KDJ_K'] = round(latest['K'], 2) if pd.notna(latest['K']) else None
                
                comparison_data.append(result)
                
            except Exception as e:
                import traceback
                error_msg = traceback.format_exc()
                logging.error(f"分析股票 {stock_code} 时出错: {str(e)}")
                logging.error(f"详细错误信息:\n{error_msg}")
                # 将错误信息也添加到结果中，方便调试
                comparison_data.append({
                    '股票代码': stock_code,
                    '股票名称': f'错误: {stock_code}',
                    '综合评分': 0,
                    '投资建议': f'分析失败: {str(e)[:50]}',
                    '错误详情': str(e)
                })
                continue
        
        if not comparison_data:
            logging.warning("没有成功分析的股票")
            return pd.DataFrame()
        
        # 转换为DataFrame并排序
        df = pd.DataFrame(comparison_data)
        df = df.sort_values('综合评分', ascending=False)
        
        logging.info(f"对比分析完成，共分析 {len(df)} 只股票")
        return df
    
    def find_best_stocks(self, stock_codes: List[str], top_n=5) -> pd.DataFrame:
        """
        从股票列表中找出得分最高的N只股票
        
        参数:
            stock_codes: 股票代码列表
            top_n: 返回前N只
        
        返回:
            DataFrame: 排名前N的股票
        """
        df = self.analyze_multiple_stocks(stock_codes)
        
        if len(df) == 0:
            return df
        
        return df.head(top_n)
    
    def compare_similar_stocks(self, base_stock_code: str, similar_codes: List[str]) -> Dict:
        """
        对比相似股票（如同行业股票）
        
        参数:
            base_stock_code: 基准股票代码
            similar_codes: 相似股票代码列表
        
        返回:
            Dict: 对比结果
        """
        all_codes = [base_stock_code] + similar_codes
        df = self.analyze_multiple_stocks(all_codes)
        
        if len(df) == 0:
            return {}
        
        # 找出基准股票的排名
        base_rank = df[df['股票代码'] == base_stock_code].index[0] + 1 if base_stock_code in df['股票代码'].values else None
        
        return {
            'comparison_table': df,
            'base_stock': base_stock_code,
            'base_rank': base_rank,
            'total_count': len(df),
            'better_than_base': (base_rank - 1) if base_rank else 0,
            'worse_than_base': (len(df) - base_rank) if base_rank else 0
        }

